<template>
  <div class="jcdManagement">
    <div class="t_fm">
      <el-upload
        class="upload-demo"
        :before-upload="handleZyzc"
        :show-file-list="false"
        multiple
        action=""
      >
        <el-button type="primary">资源资产文件上传.zip</el-button>
      </el-upload>
      <el-upload
        class="upload-demo"
        :before-upload="handleWydc"
        :show-file-list="false"
        multiple
        action=""
      >
        <el-button type="primary">外业调查文件上传.zip</el-button>
      </el-upload>
      <el-button type="warning" @click="handDataValidation">数据验证</el-button>
    </div>

    <el-tabs v-model="activeTab">
      <el-tab-pane label="资源资产文件数据" name="zyzcData">
        <el-table :data="zyzcPaginatedData" border style="width: 100%">
          <el-table-column prop="XZQMC" label="行政区名称"></el-table-column>
          <el-table-column
            prop="GTDCTBBSM"
            label="国土调查图斑标识码"
            min-width="160"
          ></el-table-column>
          <el-table-column prop="GTDCDLMC" label="地类名称"></el-table-column>
          <el-table-column prop="ZTBMJ" label="子图斑面积"></el-table-column>
          <el-table-column prop="ZBGD" label="植被盖度"></el-table-column>
          <el-table-column prop="PJG" label="平均高"></el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                @click="handleEdit1(scope.row)"
                type="primary"
                size="mini"
                >查看</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="currentZyzcPage"
          :page-size="pageSize"
          :total="zyzcTotalItems"
          @current-change="handleZyzcCurrentChange"
        />
      </el-tab-pane>

      <el-tab-pane label="外业调查文件数据" name="wydcData">
        <el-table :data="wydcPaginatedData" border style="width: 100%">
          <el-table-column prop="YDBH" label="样地编号"></el-table-column>
          <el-table-column prop="XZQMC" label="行政区名称"></el-table-column>
          <el-table-column
            prop="GTDCTBBSM"
            label="国土调查图斑标识码"
            min-width="160"
          ></el-table-column>
          <el-table-column prop="GTDCDLMC" label="地类名称"></el-table-column>
          <el-table-column prop="ZTBMJ" label="子图斑面积"></el-table-column>
          <el-table-column prop="ZBGD" label="植被盖度"></el-table-column>
          <el-table-column prop="PJG" label="平均高"></el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button
                @click="handleEdit(scope.row)"
                type="primary"
                size="mini"
                >查看</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="currentWydcPage"
          :page-size="pageSize"
          :total="wydcTotalItems"
          @current-change="handleWydcCurrentChange"
        />
      </el-tab-pane>

      <el-tab-pane label="数据验证结果" name="validationResults">
        <el-table :data="validationPaginatedResults" border>
          <el-table-column
            prop="GTDCTBBSM"
            label="图斑标识码"
            show-overflow-tooltip
          />
          <el-table-column prop="YDBH" label="样地编号" show-overflow-tooltip />
          <el-table-column prop="DCRQ" label="调查日期" show-overflow-tooltip />
          <el-table-column prop="BZ" label="备注" show-overflow-tooltip />
          <!-- <el-table-column prop="YSZ" label="优势种" />
          <el-table-column prop="PJG" label="平均高" />
          <el-table-column prop="ZBGD" label="植被盖度" />
          <el-table-column prop="MGQGCCL" label="每公顷干草产量" /> -->

          <el-table-column
            prop="discrepancies"
            label="对比结果"
            min-width="180"
            v-if="
              Object.keys(validationResults[0] || {}).includes('discrepancies')
            "
          >
            <template slot-scope="scope">
              <!-- <div
                v-for="(value, key) in scope.row.discrepancies"
                :key="key"
                style="color: red;"
              >
                {{ value }}
              </div> -->
              <span
                v-if="
                  scope.row.discrepancies === '无样地编号,且备注或调查日期缺失'
                "
                style="color: red"
              >
                {{ scope.row.discrepancies }}
              </span>
              <span v-else>
                <div
                  v-for="(value, key) in scope.row.discrepancies"
                  :key="key"
                  style="color: red"
                >
                  {{ value }}
                </div>
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
  :current-page="currentValidationPage"
  :page-size="pageSize"
  :total="validationTotalItems"
  @current-change="handleValidationCurrentChange"
/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import shp from "shpjs";

export default {
  name: "jcdManagement",
  data() {
    return {
      zyzcData: [],
      wydcData: [],
      zyzcPaginatedData: [],
      wydcPaginatedData: [],
      currentZyzcPage: 1,
      currentWydcPage: 1,
      currentValidationPage: 1, // 验证结果当前页
      pageSize: 10,
      zyzcTotalItems: 0,
      wydcTotalItems: 0,
      validationTotalItems: 0, // 验证结果总条目数
      activeTab: "zyzcData",

      validationResults: [],
      validationPaginatedResults: [], // 验证结果分页数据
    };
  },
  computed: {
    ...mapState({
      myData: "myData",
    }),
  },
  methods: {
    ...mapActions({
      updateData: "updateMyData",
    }),
    handleEdit(row) {
      this.$router.replace({ name: "shapeData", params: row });
    },
    handleEdit1(row) {
      this.$router.replace({ name: "shapeData1", params: row });
    },
    handleWydc(file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        shp(event.target.result).then((geojson) => {
          this.wydcData = geojson.features.map((feature) => feature.properties);
          console.log("最初的数据", this.wydcData);

          this.wydcTotalItems = this.wydcData.length;
          this.paginateWydcData();
        });
      };
      reader.readAsArrayBuffer(file);
    },
    handleZyzc(file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        shp(event.target.result).then((geojson) => {
          this.zyzcData = geojson.features.map((feature) => feature.properties);
          this.zyzcTotalItems = this.zyzcData.length;
          this.paginateZyzcData();
        });
      };
      reader.readAsArrayBuffer(file);
    },
    paginateWydcData() {
      const start = (this.currentWydcPage - 1) * this.pageSize;
      this.wydcPaginatedData = this.wydcData.slice(
        start,
        start + this.pageSize
      );
    },
    paginateZyzcData() {
      const start = (this.currentZyzcPage - 1) * this.pageSize;
      this.zyzcPaginatedData = this.zyzcData.slice(
        start,
        start + this.pageSize
      );
    },
    handleWydcCurrentChange(page) {
      this.currentWydcPage = page;
      this.paginateWydcData();
    },
    handleZyzcCurrentChange(page) {
      this.currentZyzcPage = page;
      this.paginateZyzcData();
    },
    // handDataValidation() {
    //   // Your validation logic here
    //   if (this.wydcData.length == 0) {
    //     this.$message.warning("请上传草原外业调查数据！");
    //     return;
    //   }
    //   if (this.zyzcData.length == 0) {
    //     this.$message.warning("请上传草原资源资产数据！");
    //     return;
    //   }

    //   this.validationResults = [];
    //   console.log("数据", this.wydcData);

    //   // this.wydcData.forEach((item) => {
    //   //   const { YDBH, DCRQ, bz } = item;
    //   //   console.log("日期", DCRQ);

    //   //   if (YDBH) {
    //   //     // 有样地编号，检查调查日期和备注
    //   //     const formattedDate = new Date(DCRQ);
    //   //     const displayDate = isNaN(formattedDate)
    //   //       ? "未填写"
    //   //       : formattedDate.toISOString().split("T")[0];
    //   //     // const dcrqValue = DCRQ ? DCRQ : "未填写";
    //   //     const bzValue = bz ? bz : "未填写";
    //   //     this.validationResults.push({
    //   //       GTDCTBBSM: item.GTDCTBBSM,
    //   //       YDBH,
    //   //       DCRQ: displayDate,
    //   //       bz: bzValue,
    //   //     });
    //   //   } else if (!DCRQ && bz) {
    //   //     // 有备注，无样地编号和调查日期，正常，不需显示
    //   //     return;
    //   //   }
    //   // });

    //   this.wydcData.forEach((wydcItem) => {
    //     const { GTDCTBBSM, YDBH, DCRQ, bz, YSZ, PJG, ZBGD, MGQGCCL } = wydcItem;
    //   const formattedDate = new Date(DCRQ);
    //       const displayDate = isNaN(formattedDate)
    //         ? "未填写"
    //         : formattedDate.toISOString().split("T")[0];
    //     if (YDBH) {
    //       const zyzcItem = this.zyzcData.find(
    //         (item) => item.GTDCTBBSM === GTDCTBBSM
    //       );

    //       if (zyzcItem) {
    //         let discrepancies = {};
    //         if (zyzcItem.YSZ !== YSZ) {
    //           discrepancies.YSZ = `优势种: ${zyzcItem.YSZ} 与调查值: ${YSZ}不相符`;
    //         }
    //         if (zyzcItem.PJG !== PJG) {
    //           discrepancies.PJG = `平均高: ${zyzcItem.PJG}与调查值: ${PJG}不相符`;
    //         }
    //         if (zyzcItem.ZBGD !== ZBGD) {
    //           discrepancies.ZBGD = `植被盖度: ${zyzcItem.ZBGD} 与调查值: ${ZBGD}不相符`;
    //         }
    //         if (zyzcItem.MGQGCCL !== MGQGCCL) {
    //           discrepancies.MGQGCCL = `每公顷干草产量: ${zyzcItem.MGQGCCL} 与调查值: ${MGQGCCL}不相符`;
    //         }

    //         this.validationResults.push({
    //           GTDCTBBSM,
    //           YDBH,
    //           DCRQ: displayDate || "未填写",
    //           bz: bz || "未填写",
    //           YSZ,
    //           PJG,
    //           ZBGD,
    //           MGQGCCL,
    //           discrepancies:
    //             Object.keys(discrepancies).length > 0 ? discrepancies : null,
    //         });
    //       }
    //     }

    //   });

    //   if (this.validationResults.length === 0) {
    //     this.$message.success("所有数据一致，没有发现差异。");
    //   } else {
    //     this.activeTab = "validationResults"; // 切换到结果标签页
    //   }
    // },
      // 分页方法
  paginateValidationResults() {
    const start = (this.currentValidationPage - 1) * this.pageSize;
    this.validationPaginatedResults = this.validationResults.slice(
      start,
      start + this.pageSize
    );
  },
  
  handleValidationCurrentChange(page) {
    this.currentValidationPage = page;
    this.paginateValidationResults();
  },


    handDataValidation() {
      if (this.wydcData.length == 0) {
        this.$message.warning("请上传草原外业调查数据！");
        return;
      }
      if (this.zyzcData.length == 0) {
        this.$message.warning("请上传草原资源资产数据！");
        return;
      }

      this.validationResults = [];
      this.validationPaginatedResults = []; // 清空分页数据

      this.wydcData.forEach((wydcItem) => {
        const { GTDCTBBSM, YDBH, DCRQ, BZ, YSZ, PJG, ZBGD, MGQGCCL } = wydcItem;
        const formattedDate = new Date(DCRQ);
        const displayDate = isNaN(formattedDate)
          ? "未填写"
          : formattedDate.toISOString().split("T")[0];

        // 检查样地编号是否存在
        if (!YDBH) {
          console.log("222", BZ);
          console.log("333", displayDate);

          if (!BZ || displayDate == "未填写") {
            // console.log("数据", validationResults);

            // 无样地编号且无备注，展示该条数据
            this.validationResults.push({
              GTDCTBBSM,
              YDBH: "无",
              DCRQ: displayDate || "未填写",
              BZ: BZ || "未填写",
              discrepancies: "无样地编号,且备注或调查日期缺失",
            });
          }
          // 如果有备注，则跳过该条数据，不展示
          return;
        }

        // 样地编号存在，进行数据比对
        const zyzcItem = this.zyzcData.find(
          (item) => item.GTDCTBBSM === GTDCTBBSM
        );

        if (zyzcItem) {
          let discrepancies = {};
          if (zyzcItem.YSZ !== YSZ) {
            discrepancies.YSZ = `优势种: ${zyzcItem.YSZ} 与调查值: ${YSZ}不相符`;
          }
          if (zyzcItem.PJG !== PJG) {
            discrepancies.PJG = `平均高: ${zyzcItem.PJG} 与调查值: ${PJG}不相符`;
          }
          if (zyzcItem.ZBGD !== ZBGD) {
            discrepancies.ZBGD = `植被盖度: ${zyzcItem.ZBGD} 与调查值: ${ZBGD}不相符`;
          }
          if (zyzcItem.MGQGCCL !== MGQGCCL) {
            discrepancies.MGQGCCL = `每公顷干草产量: ${zyzcItem.MGQGCCL} 与调查值: ${MGQGCCL}不相符`;
          }

          this.validationResults.push({
            GTDCTBBSM,
            YDBH,
            DCRQ: displayDate || "未填写",
            BZ: BZ || "未填写",
            YSZ,
            PJG,
            ZBGD,
            MGQGCCL,
            discrepancies:
              Object.keys(discrepancies).length > 0 ? discrepancies : null,
          });
        }
      });

      if (this.validationResults.length === 0) {
        this.$message.success("所有数据一致，没有发现差异。");
      } else {
        this.validationTotalItems = this.validationResults.length;
      this.paginateValidationResults(); // 初始化分页数据
      this.activeTab = "validationResults"; // 切换到结果标签页
        // this.activeTab = "validationResults"; // 切换到结果标签页
      }
    },
  },
  created() {
    this.zyzcData = this.myData;
    this.zyzcTotalItems = this.zyzcData.length;
    this.paginateZyzcData();
  },
};
</script>

<style>
.upload-demo {
  display: inline-block;
  margin-right: 10px;
}
</style>
